import random
import httpx
import os
from moviepy.editor import VideoFileClip, clips_array
from moviepy.video.compositing.concatenate import concatenate_videoclips

from moviepy.audio.AudioClip import AudioClip
from moviepy.audio.io.AudioFileClip import AudioFileClip

from src.Snowflake import SnowflakeIDGenerator
from decimal import Decimal
import ffmpeg
import subprocess


def add_audio_to_video(video_path, audio_path, output_path):
    # # 打开视频文件
    # video_clip = VideoFileClip(video_path)
    #
    # # 打开音频文件
    # audio_clip = AudioFileClip(audio_path)
    #
    # # 将音频添加到视频中
    # video_clip = video_clip.set_audio(audio_clip)
    #
    # # 保存输出视频文件
    # video_clip.write_videofile(output_path, codec="libx264", preset="ultrafast", audio_codec="aac")
    # 构建 ffmpeg 命令
    if os.path.exists(output_path):
        print(f"{output_path} exists.")
        return
    command = [
        'ffmpeg',
        '-i', video_path,  # 输入视频文件路径
        '-i', audio_path,  # 输入音频文件路径
        '-c:v', 'copy',  # 使用视频流的编解码器
        '-c:a', 'aac',  # 使用 AAC 编解码器
        '-strict', 'experimental',
        '-map', '0:v:0',  # 映射视频流
        '-map', '1:a:0',  # 映射音频流
        '-shortest',  # 选择最短的输入文件时长作为输出时长
        output_path,  # 输出文件路径
        '-y'  # 允许覆盖
    ]

    # 执行 ffmpeg 命令
    subprocess.run(command, check=True)

if __name__ == "__main__":
    # 转义用户输入的字符串
    audio_name = "2024-02-14 18.25.03-妙卡-0108 r@R.Kj 单身狗们 快乐"
    audio_file = f"music/{audio_name}.mp3"
    file = f"./outputRepaired/7163801230832046080.mp4"
    out_put = f"output\\{SnowflakeIDGenerator().generate_id()}.mp4"
    add_audio_to_video(file, audio_file, out_put)
